/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.geektimes.rest.client.invocation;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URI;
import java.util.Map;
import java.util.Objects;

/**
 * HTTP POST Method {@link Invocation}
 *
 * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
 */
public class HttpPostInvocation extends HttpInvocation {

    public HttpPostInvocation(URI uri, MultivaluedMap<String, Object> headers, Map<String, Object> properties, Entity<?> entity) {
        super(uri, headers, properties, entity);
    }

    @Override
    protected void buildRequest(HttpURLConnection connection) throws IOException {
        connection.setRequestMethod(HttpMethod.POST);
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        //POST参数
        String params = buildRequestParam();
        if(StringUtils.isNotBlank(params)){
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(params.getBytes());
        }
        if(null != entity && null != entity.getEntity()){
            connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            OutputStream outputStream = connection.getOutputStream();
            ObjectMapper objectMapper = new ObjectMapper();
            outputStream.write(objectMapper.writeValueAsBytes(entity.getEntity()));
        }
    }

    private String buildRequestParam(){
        if(Objects.isNull(properties) || properties.isEmpty()){
            return "";
        }
        StringBuilder params = new StringBuilder();
        for(String key : properties.keySet()){
            params.append(key).append("=").append(properties.get(key));
        }
        return params.toString();
    }


}
